package com.haidechizi.leetcode;

import java.util.concurrent.ExecutionException;

/**
 * @author: wangdejun
 * @create: 2020-04-03 11:21
 **/
public class _8_字符串转换整数 {

    public int myAtoi(String str) {
        StringBuilder sb = new StringBuilder();

        str = str.replaceAll(" ", "");
        char[] chars = str.toCharArray();
        for (char cha : chars) {
            if (isValid(cha)) {
                sb.append(cha);
            } else {
                if (f) {
                    return 0;
                }
            }
        }
        try {
            return Integer.parseInt(sb.toString());
        } catch (Exception e) {
            return sb.charAt(0) == '-' ? Integer.MIN_VALUE : Integer.MAX_VALUE;
        }
    }


    boolean isFirst = true;
    private boolean flag = false;

    boolean f = false;

    /**
     * flag=true表示已出现-号
     *
     * @param cha
     * @return
     */
    private boolean isValid(char cha) {
        if (!flag && '-' == cha && isFirst) {
            flag = true;
            return true;
        }
        String s = String.valueOf(cha);
        if ("0123.456789".contains(s)) {
            isFirst = false;
            return true;
        }
        if (isFirst) {
            f = true;
        }
        return false;
    }

    public static void main(String[] args) {
        String str = "91283472332";
        int val  = Integer.parseInt(str);
        System.out.println(val);
    }


}
